var $ = getApp().globalData.eui;
$.page({
	data: {},
	onLoad: function (options) {

		var me = this;

	},
	onGetUserInfo: function (e) {

		var me = this;

		var detail = e.detail;

		if (detail.errMsg == "getUserInfo:ok") {
			var userInfo = detail.userInfo;
			userInfo.encryptedData = detail.encryptedData;
			userInfo.iv = detail.iv;
			$.setKey("userInfo", $.toJson(userInfo));
			console.log("保存用户信息：" + userInfo.nickName);
			//me.notify("Authed", [true]);
			//me.notify("UserInfo", [userInfo]);
			var sex = ($.toInt(userInfo.gender) === 2 ? 1 : 0);
			$.wx_login({})
				.then(function (res) {
					var code = res.code;
					return $.api("site.Sys.MiniLogin", {
						encryptedData: userInfo.encryptedData,
						iv: userInfo.iv,
						alias: userInfo.nickName,
						sex: sex,
						icon: userInfo.avatarUrl,
						code: code
					});
				}, function (err) {
					$.log(err.errMsg);
				})
				.then(function (value) {
					console.log("登录成功，保存sid:" + $.toJson(value));
					//me.notify("Logined", [true]);
					$.hasKey("needBindUser")
						.then(function (b) {
							if (b) {
								$.getKey("needBindUser").then(function (fromUser) {
									fromUser = $.toInt(fromUser);
									$.api("mall.User.Bind", {
										pid: fromUser
									})
										.then(function (value) {
											$.removeKey("needBindUser").then(function () {
												//do nothing
											})
										});
								})
							}
						});
					return $.setSessionKey(value);
				}, function () {
					$.back();
				})
				.then(function (sid) {
					getApp().getLoginUser(function (oUser) {
						me.notify("Login", [oUser]);
						$.back();
					}, function () {
						$.back();
					})
				}, function (err) {
					$.errorBox("错误", err.message);
				});
		}
	}
})


